import pyautogui
import time
from pynput import keyboard

# 全局控制开关
auto_fight_running = False

# 基础操作函数
def select_target():
    pyautogui.press('tab')

def cast_spell():
    pyautogui.press('3')

def physical_attack():
    pyautogui.press('2')

def use_skill1():
    pyautogui.press('4')

def use_skill2():
    pyautogui.press('5')

def pickup():
    pyautogui.press('`')

# 移动角色
def move_around():
    screen_width, screen_height = pyautogui.size()
    center_x, center_y = screen_width // 2, screen_height // 2
    directions = [
        (center_x, center_y - 500),  # 上
        (center_x, center_y + 500),  # 下
        (center_x - 500, center_y),  # 左
        (center_x + 500, center_y)   # 右
    ]
    for x, y in directions:
        if x < 0: x = 0
        if x >= screen_width: x = screen_width - 1
        if y < 0: y = 0
        if y >= screen_height: y = screen_height - 1
        pyautogui.click(x, y)
        time.sleep(2)
        select_target()
        time.sleep(2)

# 攻击循环
def attack_sequence():
    # 法术攻击阶段
    cast_spell()
    time.sleep(15)
    
    # 物理攻击阶段
    physical_attack()
    time.sleep(3)
    
    # 技能阶段
    pyautogui.press('2')
    time.sleep(5)
    use_skill2()
    time.sleep(2)
    use_skill1()

# 主循环
def auto_fight_loop():
    global auto_fight_running
    
    while auto_fight_running:
        select_target()
        time.sleep(2)
        
        print("开始攻击循环")
        attack_sequence()
        time.sleep(2)

        print("执行拾取操作")
        pickup()
        time.sleep(2)

# 键盘控制
def on_press(key):
    global auto_fight_running
    try:
        if key == keyboard.Key.f3:
            auto_fight_running = not auto_fight_running
            print(f"自动打怪 {'已启动' if auto_fight_running else '已停止'}")
    except:
        pass

# 主函数
def main():
    # 启动监听
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    
    print("按F3开始/停止自动打怪")
    try:
        while True:
            if auto_fight_running:
                auto_fight_loop()
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("程序退出")

if __name__ == "__main__":
    main()